package org.raymond.iworks.study.netty.atguigu.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.net.URI;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
public class TestServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if(msg instanceof HttpRequest httpMsg){
            URI uri = new URI(httpMsg.uri());
            if("/favicon.ico".equalsIgnoreCase(uri.getPath())){
                log.info("请求了favicon.ico");
                return;
            }
            log.info("{}->{}", ctx.channel().remoteAddress(), httpMsg.getClass());

            ByteBuf content = Unpooled.copiedBuffer("hello, 我是服务器1!", CharsetUtil.UTF_8);
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            //response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain;charset=UTF-8");
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

            ctx.writeAndFlush(response);
        }else{
            log.info("msg is not httpRequest. {}", msg.getClass());
        }
    }
}
